import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as todoActions from '../store/actions/todo.actions'
import {getIn} from 'immutable'
class Main extends Component {

  componentDidMount() {
    // 调用具体的指令触发数据获取
    this.props.load_todo()
  }
  removeTask(id) {
    if (window.confirm('确认要删除吗')) {
      this.props.remove_todo(id)
    }
  }
  modify_name(id,ev){
    // 切换状态
    this.props.modify_todo_edit({id:id,isEditing:false})
    // 修改数据
    this.props.modify_todo_edit({id:id,taskName:ev.target.value})
  }
  render() {

    return (
      <section className='main'>
        <input className='toggle-all' type='checkbox' />
        <ul className='todo-list'>
          {
            this.props.todos.map(item => {
              let classes = []
              if(item.isCompleted) classes.push('completed')
              if(item.isEditing) classes.push('editing')
              return (
                <li key={item.id} className={classes.join(' ')}>
                  <div className='view'>
                    <input
                      className='toggle'
                      type='checkbox'
                      defaultChecked={item.isCompleted}
                      onChange={(e) => { this.props.modify_todo({ id: item.id, isCompleted: e.target.checked }) }}
                    />
                    <label onDoubleClick={() => { this.props.modify_todo_edit({ id: item.id, isEditing: true }) }}>{item.taskName}</label>
                    <button className='destroy' onClick={this.removeTask.bind(this, item.id)}></button>
                  </div>
                  <input 
                    className='edit' 
                    defaultValue={item.taskName}
                    onBlur = {this.modify_name.bind(this,item.id)} 
                  />
                </li>
              )
            })
          }
        </ul>
      </section>
    )
  }
}

// 获取store中的数据
const mapStateToProps = (state) => ({
  todos:filterTodos(getIn(state.todoReducer,['todos']),getIn(state.todoReducer,['filter']))
})

const mapDispatchToProps = (dispatch) => ({
  ...bindActionCreators(todoActions, dispatch)
})

// 实现过滤数据
function filterTodos(todos, filter) {
  switch (filter) {
    case 'all':
      return todos
    case 'active':
      return todos.filter(todo => !todo.isCompleted)
    case 'completed':
      return todos.filter(todo => todo.isCompleted)
    default:
      return
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Main)